package com.gitee.gphomework.mybatis.typehandler;

import com.gitee.gphomework.mybatis.typehandler.dao.MerchantDao;
import com.gitee.gphomework.mybatis.typehandler.entity.Merchant;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * Created on 2020/5/9
 * Title: 入口类
 * Description: 入口类
 * Copyright: Copyright(c) 2020
 * Company:
 *
 * @author yifeng
 */
public class Main {

    public static final String MYBATIS_CONFIG = "mybatis-config.xml";

    public static SqlSessionFactory sqlSessionFactory;

    static {
        ClassLoader cl = Main.class.getClassLoader();
        if (cl == null) {
            cl = Thread.currentThread().getContextClassLoader();
        }
        Objects.requireNonNull(cl);
        InputStream is = cl.getResourceAsStream(MYBATIS_CONFIG);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    }

    public static void main(String[] args) {
        Merchant merchant = new Merchant();
        List<Integer> businessScope = Arrays.asList(1, 2, 3);
        merchant.setName("商户1");
        merchant.setBusinessScope(businessScope);
        insertMerchant(merchant);
        List<Merchant> merchants = selectAllMerchant(new Merchant());
        System.out.println(Arrays.toString(merchants.toArray()));
    }

    private static void insertMerchant(Merchant merchant) {
        Objects.requireNonNull(merchant);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        try {
            MerchantDao merchantDao = sqlSession.getMapper(MerchantDao.class);
            merchantDao.insert(merchant);
            System.out.println("insert successfully");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Optional.ofNullable(sqlSession).ifPresent(SqlSession::close);
        }
    }

    private static List<Merchant> selectAllMerchant(Merchant merchant) {
        Objects.requireNonNull(merchant);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        List<Merchant> merchants = null;
        try {
            MerchantDao merchantDao = sqlSession.getMapper(MerchantDao.class);
            merchants = merchantDao.select(merchant);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Optional.ofNullable(sqlSession).ifPresent(SqlSession::close);
        }
        return merchants;
    }

}
